package com.ldk.api.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ldk.base.framework.util.*;

import com.ldk.framework.entity.*;
import com.ldk.framework.enums.DriverCheckStatus;
import com.ldk.framework.service.*;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.ldk.api.ApiVersion;
import com.ldk.api.CheckToken;
import com.ldk.api.ErrorCode;
import com.ldk.api.FileItem;
import com.ldk.api.RequestPlatform;
import com.ldk.api.ResponseObject;
import com.ldk.api.ResponseResult;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.framework.enums.CashApplyStatus;
import com.ldk.framework.enums.DriverStatus;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.RechargeType;
import com.ldk.framework.enums.ServiceCode;
import com.ldk.framework.enums.TripStatus;
import com.ldk.framework.enums.UserStatus;

/**
 * 司机模块
 *
 * @author xiangwl
 * 2017年2月21日
 * com.ldk.api.handler
 * DriverRequestHandler
 */
public class DriverRequestHandler extends BaseRequestHandler {

    @Autowired
    private IDriverService driverService;
    @Autowired
    private IPhoneValidcodeService phoneValidcodeService;
    @Autowired
    private IRechargeRecordService rechargeRecordService;
    @Autowired
    private IDriverCarImgsService driverCarImgsService;
    @Autowired
    private ICommentService commentService;
    @Autowired
    private ICashApplyService cashApplyService;
    @Autowired
    private ICashRecordService cashRecordService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IServiceTripService serviceTripService;
    @Autowired
    private IOperateLoginService operateLoginService;
    @Autowired
    private IPositionVehicleService positionVehicleService;
    @Autowired
    private IPositionDriverService positionDriverService;
    @Autowired
    private IOperateLogoutService operateLogoutService;
    @Autowired
    private IPlatformDriverService platformDriverService;
    @Autowired
    private IVehicleService vehicleService;
    @Autowired
    private ITicketUserService ticketUserService;

    /**
     * 注册司机(基础信息)
     *
     * @param parms phoneNo        手机号
     *              idCard         身份证
     *              validCode      验证码
     *              pwd            密码
     *              trueName       真实姓名
     *              sex            性别
     *              bankCard       银行卡号
     *              bankName       银行名称
     *              driveAge       驾龄
     *              driveCret      驾驶证
     *              netCert        网约车资格证
     *              runCert        运营证
     *              carNo          车牌号
     *              carType        车类型
     *              carRank        车等级
     *              carColor       车颜色
     *              lon            当前位置经度
     *              lat            当前位置纬度
     *              headImg        头像
     *              idCardFrontImg 身份证正面照片
     *              idCardBackImg  身份证背面照片
     *              driveCretImg   驾驶证照片
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject registerForBasic(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "registerForBasic");
        //ycs 190305
        //参数验证
        if (!checkRequireParms(parms, "phoneNo", "idCard", "validCode", "pwd",
                "trueName", "sex", "driveAge", "driveCret", "carNo", "carType", "carBrand", "carSeats",
                "carRank", "carColor", "idCardFrontImg",
                "idCardBackImg", "driveCretImg")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        String validCode = ConvertUtil.parseString(parms.get("validCode"));
        //ycs 190305
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (phoneValidcodeService.checkExpired("", phoneNo, validCode)) {
            return ResponseResult.exception(response, ErrorCode.VALIDE_CODE_TIME_OUT);
        }

        String idCard = ConvertUtil.parseString(parms.get("idCard"));
        String pwd = ConvertUtil.parseString(parms.get("pwd"));
        String trueName = ConvertUtil.parseString(parms.get("trueName"));
        String sex = ConvertUtil.parseString(parms.get("sex"));
        String bankCard = ConvertUtil.parseString(parms.get("bankCard"));
        String bankName = ConvertUtil.parseString(parms.get("bankName"));
        int driveAge = ConvertUtil.parseInt(parms.get("driveAge"));
        String driveCret = ConvertUtil.parseString(parms.get("driveCret"));
        //String netCert = ConvertUtil.parseString(parms.get("netCert"));
        //String runCert = ConvertUtil.parseString(parms.get("runCert"));
        String carNo = ConvertUtil.parseString(parms.get("carNo"));
        String carType = ConvertUtil.parseString(parms.get("carType"));
        String carRank = ConvertUtil.parseString(parms.get("carRank"));
        String carColor = ConvertUtil.parseString(parms.get("carColor"));
        String carBrand = ConvertUtil.parseString(parms.get("carBrand"));
        int carSeats = ConvertUtil.parseInt(parms.get("carSeats"), 0);
        double lon = ConvertUtil.parseDouble(parms.get("lon"));
        double lat = ConvertUtil.parseDouble(parms.get("lat"));
        String headImg = ConvertUtil.parseString(parms.get("headImg"));
        String idCardFrontImg = ConvertUtil.parseString(parms.get("idCardFrontImg"));
        String idCardBackImg = ConvertUtil.parseString(parms.get("idCardBackImg"));
        String driveCretImg = ConvertUtil.parseString(parms.get("driveCretImg"));

        //ycs 190305
        if (StringUtils.isBlank(phoneNo) || StringUtils.isBlank(idCard)
                || StringUtils.isBlank(pwd) || StringUtils.isBlank(trueName)
                || StringUtils.isBlank(driveCret) || StringUtils.isBlank(carNo)
                || StringUtils.isBlank(carRank)
                || StringUtils.isBlank(idCardFrontImg)
                || StringUtils.isBlank(idCardBackImg)
                || StringUtils.isBlank(driveCretImg)) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        Driver query = new Driver();
        query.setPhoneNo(phoneNo);
        Driver entity = driverService.selectOne("", query);
        if (entity != null) {
            if (entity.getCheckState() == 0) {
                //司机已存在，且审核通过
                return ResponseResult.exception(response, ErrorCode.DRIVER_CHECK_ING);
            }
            if (entity.getCheckState() == 1) {
                //司机已存在，且审核通过
                return ResponseResult.exception(response, ErrorCode.DRIVER_EXIST);
            }
        }
        //查询该车辆是否存在系统中
        Vehicle queryv = new Vehicle();
        queryv.setVehicleNo(carNo);
        queryv.setEnabled(true);
        Vehicle vehicle1 = vehicleService.selectOne("", queryv);
        //if (vehicle1 != null) {
        //    return ResponseResult.exception(response, ErrorCode.Vehicle_EXIST);
        //}

        /*long count = driverService.selectCount("", query);
        if (count > 0) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_EXIST);
        }*/

        Boolean success = false;
        try {
            String openId = "";
            String slat = SystemUtil.generateSalt(6);
            if (entity == null) {
                entity = new Driver();
                //生成openId
                openId = OpenIdUtil.encrypt(entity.getPhoneNo() + entity.getIdCard(), SystemUtil.getAllSeconds(), slat);
                entity.setOpenId(openId);
                String token = TokenUtil.encrypt(phoneNo, openId);
                entity.setToken(token);
            }
            entity.setPhoneNo(phoneNo);
            entity.setIdCard(idCard);
            entity.setTrueName(trueName);
            String encryptPwd = EncryptUtil.md5(pwd + slat);
            entity.setPwd(encryptPwd);
            entity.setSlat(slat);
            entity.setSex(sex);
            entity.setBankCard(bankCard);
            entity.setBankName(bankName);
            entity.setDriveAge(driveAge);
            entity.setDriveCret(driveCret);
            //entity.setNetCert(netCert);
            //entity.setRunCert(runCert);
            entity.setCarNo(carNo);
            entity.setCarRank(carRank);
            entity.setCarType(carType);
            entity.setCarColor(carColor);
            entity.setCarBrand(carBrand);
            entity.setLon(lon);
            entity.setLat(lat);
            entity.setHeadImg(headImg);
            entity.setIdCardFrontImg(idCardFrontImg);
            entity.setIdCardBackImg(idCardBackImg);
            entity.setDriveCretImg(driveCretImg);

            //默认值
            entity.setCarSeats(carSeats);
            entity.setStar(3.0);
            entity.setBalance(0.0);
            entity.setIncome(0.0);
            entity.setCash(0.0);
            entity.setStatus(DriverStatus.OffLine.getValue());
            entity.setOrderCount(0);
            entity.setCancelTripTimes(0);
            entity.setDisableDays(0);
            entity.setDisableDate(0L);
            entity.setAreaCode("520100");
            entity.setOperator("APP注册");
            entity.setOperateTime(SystemUtil.getAllSeconds());
            entity.setEnabled(true);
            //如果车辆信息存在，则默认审核通过
            if (vehicle1 != null) {
                entity.setCheckState(DriverCheckStatus.CheckSusses.getValue());
            } else {
                entity.setCheckState(DriverCheckStatus.WaitCheck.getValue());
            }

            entity.setBindCar(true);
            entity.setSourceType(0);
            entity.setScore(100.0);

            entity.setAreaCode("520100");
            entity.setAreaName("贵阳市");

            //手机注册，默认为快车和专车司机
            entity.setServiceCodes(ServiceCode.KC.getCode() + "," + ServiceCode.ZC.getCode());
            entity.setServiceNames(ServiceCode.KC.getName() + "," + ServiceCode.ZC.getName());
            logger.error("entity=" + JSON.toJSONString(entity));
            int row = 0;
            if (entity.getDriverId() != null && entity.getDriverId() > 0) {
                logger.error("row=" + 0);
                row = driverService.updateByKey("", entity);
            } else {
                logger.error("row=" + 1);
                row = driverService.insert("", entity);
            }
            success = row > 0;
            if (success) {
                //APP注册的，需审核成功后，插入车辆信息表
                /*Vehicle vehicle = new Vehicle();
                vehicle.setVehicleNo(carNo);
                vehicle.setBrand(carBrand);
                vehicle.setModel(carRank);
                vehicle.setVehicleType(carType);
                vehicle.setVehicleColor(carColor);
                vehicle.setSeats(Long.parseLong(carSeats + ""));
                vehicle.setDatetime(SystemUtil.getAllSeconds());
                vehicle.setEnabled(true);
                vehicle.setDriverOpenId(openId);
                vehicleService.insert("", vehicle);*/
            }
            // 奖励现金卷或优惠卷
            /*if (rCommonId > 0) {
                query = new Driver();
                query.setPhoneNo(phoneNo);
                Driver driver = driverService.selectOne("", query);
                driverService.insertCoupon(driver);
            }*/
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "注册成功");
        } else {
            ResponseResult.exception(response, ErrorCode.DRIVER_REGISTER_FAILED);
        }
        return response;
    }

    /**
     * 注册身份证正面照片
     *
     * @param parms phoneNo  手机号
     *              fileList
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject registerForIdCardFrontImg(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "registerForIdCardFrontImg");
        //参数验证
        if (!checkRequireParms(parms, "phoneNo", "fileList")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        Driver query = new Driver();
        query.setPhoneNo(phoneNo);
        Driver driver = driverService.selectOne("", query);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        List<FileItem> fileList = null;
        if (parms.get("fileList") != null) {
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> list = (List<FileItem>) parms.get("fileList");
                fileList = list;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        if (fileList == null ||
                fileList.isEmpty() ||
                StringUtils.isBlank(fileList.get(0).getFileFullUrl())) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_IDCARD_IMAGE_EMPTY);
        }
        String idCardFrontImg = fileList.get(0).getFileFullUrl();
        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setIdCardFrontImg(idCardFrontImg);

            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "");
        } else {
            ResponseResult.exception(response, ErrorCode.DRIVER_IDCARD_IMAGE_FAILED);
        }
        return response;
    }

    /**
     * 注册身份证背面照片
     *
     * @param parms phoneNo  手机号
     *              fileList
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject registerForIdCardBackImg(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "registerForIdCardBackImg");
        //参数验证
        if (!checkRequireParms(parms, "phoneNo", "fileList")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        Driver query = new Driver();
        query.setPhoneNo(phoneNo);
        Driver driver = driverService.selectOne("", query);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        List<FileItem> fileList = null;
        if (parms.get("fileList") != null) {
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> list = (List<FileItem>) parms.get("fileList");
                fileList = list;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        if (fileList == null ||
                fileList.isEmpty() ||
                StringUtils.isBlank(fileList.get(0).getFileFullUrl())) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_IDCARD_IMAGE_EMPTY);
        }
        String idCardBackImg = fileList.get(0).getFileFullUrl();
        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setIdCardBackImg(idCardBackImg);

            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "");
        } else {
            ResponseResult.exception(response, ErrorCode.DRIVER_IDCARD_IMAGE_FAILED);
        }
        return response;
    }

    /**
     * 注册驾驶证照片
     *
     * @param parms phoneNo  手机号
     *              fileList
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject registerForDriveCretImg(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "registerForDriveCretImg");
        //参数验证
        if (!checkRequireParms(parms, "phoneNo", "fileList")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        Driver query = new Driver();
        query.setPhoneNo(phoneNo);
        Driver driver = driverService.selectOne("", query);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        List<FileItem> fileList = null;
        if (parms.get("fileList") != null) {
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> list = (List<FileItem>) parms.get("fileList");
                fileList = list;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        if (fileList == null ||
                fileList.isEmpty() ||
                StringUtils.isBlank(fileList.get(0).getFileFullUrl())) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_HEAD_IMAGE_EMPTY);
        }
        String driveCretImg = fileList.get(0).getFileFullUrl();
        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setDriveCretImg(driveCretImg);

            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "");
        } else {
            ResponseResult.exception(response, ErrorCode.DRIVER_DRIVE_CRET_IMAGE_FAILED);
        }
        return response;
    }

    /**
     * 司机登录
     *
     * @param parms phoneNo 手机号
     *              pwd     登录密码(明文密码)
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject login(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "login");
        //参数验证
        if (!checkRequireParms(parms, "phoneNo", "pwd")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        String pwd = ConvertUtil.parseString(parms.get("pwd"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (StringUtils.isBlank(pwd)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }

        Driver query = new Driver();
        query.setPhoneNo(phoneNo);

        Driver driver = driverService.selectOne("", query);
        //司机不存在
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        if (!driver.getEnabled()) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_ENABLED);
        }
        if (driver.getCheckState() == DriverCheckStatus.WaitCheck.getValue()) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_CHECK_ING);
        }
        if (driver.getCheckState() == DriverCheckStatus.CheckFail.getValue()) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_CHECK_FALURE);
        }

        String slat = driver.getSlat();
        if (driver.getSourceType() == 1) {
            String encryptPwd = EncryptUtil.md5(pwd);
            query.setPwd(encryptPwd);
            query.setEnabled(true);
        } else {
            String encryptPwd = EncryptUtil.md5(pwd + slat);
            query.setPwd(encryptPwd);
            query.setEnabled(true);
        }


        driver = driverService.selectOne("", query);
        //用户名或密码错误
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_PHONE_OR_PWD_ERROR);
        }

        Boolean success = false;
        try {
            String token = TokenUtil.encrypt(driver.getPhoneNo(), driver.getOpenId());
            //修改加密盐重新加密密码
            slat = SystemUtil.generateSalt(6);
            String newEncryptPwd = EncryptUtil.md5(pwd + slat);
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            if (driver.getSourceType() != 1) {
                entity.setSlat(slat);
                entity.setPwd(newEncryptPwd);
            }
            entity.setToken(token);
            //同时修改司机状态
            entity.setStatus(DriverStatus.OnLine.getValue());
            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //重新获取司机信息，并返回
            query = new Driver();
            query.setDriverId(driver.getDriverId());
            driver = driverService.selectByKey("", query);

            response = ResponseResult.success(response, driver);
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_LOGIN_FAILED);
        }

        return response;
    }


    /**
     * 司机上线
     *
     * @param parms openId 司机openId
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverOnLine(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "driverOnLine");
        //参数验证
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        //司机不存在
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //司机在工作中
        if (driver.getStatus() == DriverStatus.Working.getValue()) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_WORKING);
        }
        //判断上一次登录时间是否在今日
        Boolean isTodayeLogin = false;
        if (driver.getLoginTime() != null && driver.getLoginTime() > 0) {
            String time = DateUtil.longToStr(driver.getLoginTime() * 1000, "yyyy-MM-dd");
            String nowtime = DateUtil.longToStr(new Date().getTime(), "yyyy-MM-dd");
            if (time.equals(nowtime)) {
                isTodayeLogin = true;
            }
        }
        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setStatus(DriverStatus.OnLine.getValue());
            if (!isTodayeLogin) {
                entity.setDuration(0l);
            }
            entity.setLoginTime(SystemUtil.getAllSeconds());
            int row = driverService.updateByKey("", entity);
            success = row > 0;

            if (success) {
                OperateLogin operateLogin = new OperateLogin();
                operateLogin.setCompanyId("5201HDCX8779");
                operateLogin.setLicenseId(driver.getIdCard());
                operateLogin.setVehicleNo(driver.getCarNo());
                operateLogin.setLoginTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                operateLogin.setLongitude(driver.getLon());
                operateLogin.setLatitude(driver.getLat());
                operateLogin.setEncrypt(3L);
                operateLogin.setLoginTime2(0L);
                operateLoginService.insertUpper("", operateLogin);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //重新获取司机返回
            Driver result = driverService.getDriverByOpenId("", openId);
            response = ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_LOGOUT_FAILED);
        }

        return response;
    }


    /**
     * 司机下线
     *
     * @param parms openId 司机openId
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject driverOffLine(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "driverOffLine");
        //参数验证
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        //司机不存在
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //司机在工作中
        if (driver.getStatus() == DriverStatus.Working.getValue()) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_WORKING);
        }
        Boolean isTodayeLogin = false;
        if (driver.getLoginTime() != null && driver.getLoginTime() > 0) {
            String time = DateUtil.longToStr(driver.getLoginTime() * 1000, "yyyy-MM-dd");
            String nowtime = DateUtil.longToStr(new Date().getTime(), "yyyy-MM-dd");
            if (time.equals(nowtime)) {
                isTodayeLogin = true;
            }
        }
        //统计本次在线时长
        long durnation = 0l;
        if (isTodayeLogin) {
            durnation = SystemUtil.getAllSeconds() - driver.getLoginTime();
        } else {
            String begindate = DateUtil.DatetoString(new Date(), "yyyy-MM-dd 00:00:00");
            long begin = DateUtil.StringtoDate(begindate, "yyyy-MM-dd HH:mm:ss").getTime() / 1000;
            durnation = SystemUtil.getAllSeconds() - begin;
        }
        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setStatus(DriverStatus.OffLine.getValue());
            entity.setDuration(durnation);
            int row = driverService.updateByKey("", entity);
            success = row > 0;

            if (success) {
                OperateLogout operateLogout = new OperateLogout();
                operateLogout.setCompanyId("5201HDCX8779");
                operateLogout.setLicenseId(driver.getIdCard());
                operateLogout.setVehicleNo(driver.getCarNo());
                operateLogout.setLogoutTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                operateLogout.setLongitude(driver.getLon());
                operateLogout.setLatitude(driver.getLat());
                operateLogout.setEncrypt(3L);
                operateLogout.setLogoutTime2(0L);
                operateLogoutService.insertUpper("", operateLogout);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            Driver result = driverService.getDriverByOpenId("", openId);
            response = ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_LOGOUT_FAILED);
        }
        return response;
    }


    /**
     * 司机修改密码
     *
     * @param parms phoneNo   手机号
     *              validCode 验证码
     *              pwd       登录密码
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject updatePwd(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "updatePwd");
        //参数验证
        if (!checkRequireParms(parms, "phoneNo", "validCode", "pwd")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        String validCode = ConvertUtil.parseString(parms.get("validCode"));
        String pwd = ConvertUtil.parseString(parms.get("pwd"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        if (StringUtils.isBlank(pwd)) {
            return ResponseResult.exception(response, ErrorCode.PASSWORD_EMPTY);
        }
        Driver query = new Driver();
        query.setPhoneNo(phoneNo);

        Driver driver = driverService.selectOne("", query);
        //司机不存在
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        //判断验证码是否过期
        if (phoneValidcodeService.checkExpired("", phoneNo, validCode)) {
            return ResponseResult.exception(response, ErrorCode.VALIDE_CODE_TIME_OUT);
        }

        Boolean success = false;
        try {
            String slat = SystemUtil.generateSalt(6);
            String newEncryptPwd = EncryptUtil.md5(pwd + slat);
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setSlat(slat);
            entity.setPwd(newEncryptPwd);

            int row = driverService.updateByKey("", entity);

            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, "修改密码成功");
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_UPDATE_PASSWORD_FAILED);
        }

        return response;
    }

    /**
     * 司机修改头像
     *
     * @param parms openId   司机openId
     *              fileList 图片列表
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject updateHeadImage(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "updateHeadImage");
        //参数验证
        if (!checkRequireParms(parms, "openId", "fileList")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        List<FileItem> fileList = null;
        if (parms.get("fileList") != null) {
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> list = (List<FileItem>) parms.get("fileList");
                fileList = list;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        if (fileList == null ||
                fileList.isEmpty() ||
                StringUtils.isBlank(fileList.get(0).getFileFullUrl())) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_HEAD_IMAGE_EMPTY);
        }
        String headImg = fileList.get(0).getFileFullUrl();
        Driver driver = driverService.getDriverByOpenId("", openId);
        //司机不存在
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setHeadImg(headImg);

            int row = driverService.updateByKey("", entity);

            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //直接修改头像参数就不去数据库查询再返回了
            //修改头像图片地址
            driver.setHeadImg(headImg);
            response = ResponseResult.success(response, driver);
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_HEAD_IMAGE_FAILED);
        }

        return response;
    }

    /**
     * 更新位置信息
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject updateLocation(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "updateLocation");
        if (!checkRequireParms(parms, "openId", "lon", "lat")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = String.valueOf(parms.get("openId"));
        double lon = ConvertUtil.parseDouble(parms.get("lon"));
        double lat = ConvertUtil.parseDouble(parms.get("lat"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setLon(lon);
            entity.setLat(lat);

            int row = driverService.updateByKey("", entity);

            success = row > 0;
            if (success) {
                PositionDriver positionDriver = new PositionDriver();
                positionDriver.setCompanyId("5201HDCX8779");
                positionDriver.setLicenseId(driver.getIdCard());
                positionDriver.setDriverRegionCode(520100L);
                positionDriver.setVehicleNo(driver.getCarNo());
                //positionDriver.setPositionTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                positionDriver.setPositionTime(SystemUtil.getAllSeconds());
                positionDriver.setLongitude(lon);
                positionDriver.setLatitude(lat);
                positionDriver.setEncrypt(3L);
                //positionDriver.setDirection(0.0D);
                // positionDriver.setElevation(0.0D);
                //positionDriver.setSpeed(0.0D);
                //positionDriver.setBizStatus(0L);
                positionDriver.setOrderId("0");
                positionDriver.setPositionTime2(0L);
                positionDriverService.insertUpper("", positionDriver);

                PositionVehicle positionVehicle = new PositionVehicle();
                positionVehicle.setCompanyId("5201HDCX8779");
                positionVehicle.setVehicleRegionCode(520100L);
                positionVehicle.setVehicleNo(driver.getCarNo());
                positionVehicle.setPositionTime(SystemUtil.getAllSeconds());
                positionVehicle.setLongitude(lon);
                positionVehicle.setLatitude(lat);
                positionVehicle.setEncrypt(3L);
                positionVehicle.setOrderId("0");
                positionVehicle.setPositionTime2(0L);
                positionVehicleService.insertUpper("", positionVehicle);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            response = ResponseResult.success(response, "更新位置成功");
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_UPDATE_LOCATION_FAILED);
        }
        return response;
    }

    /**
     * 修改银行卡号
     *
     * @param parms bankName
     *              bankCard
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject updateBankCard(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "updateBankCard");
        if (!checkRequireParms(parms, "openId", "bankName", "bankCard")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        String bankName = ConvertUtil.parseString(parms.get("bankName"));
        String bankCard = ConvertUtil.parseString(parms.get("bankCard"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (StringUtils.isBlank(bankCard)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_BANK_CARD_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        Boolean success = false;
        try {
            Driver driverEntity = new Driver();
            driverEntity.setDriverId(driver.getDriverId());
            driverEntity.setBankName(bankName);
            driverEntity.setBankCard(bankCard);

            int row = driverService.updateByKey("", driverEntity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "邦卡成功");
        } else {
            ResponseResult.exception(response, ErrorCode.DRIVER_BIND_BANK_CARD_FAILED);
        }

        return response;
    }

    /**
     * 搜索在线状态司机列表
     *
     * @param parms openId
     *              lon         位置经度
     *              lat         位置纬度
     *              serviceCode 服务业务代码
     *              carRank     汽车等级
     *              pageIndex   分页索引
     *              pageSize    分页每页条数
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject search(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "search");
        //参数验证
        if (!checkRequireParms(parms, "openId", "lon", "lat", "serviceCode",
                "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        Double lon = ConvertUtil.parseDouble(parms.get("lon"));
        Double lat = ConvertUtil.parseDouble(parms.get("lat"));
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        //String carRank = ConvertUtil.parseString(parms.get("carRank"));
        //Integer carSeats = ConvertUtil.parseInt(parms.get("carSeats"));
        Integer pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        Integer pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        CustomPageable pageable = new CustomPageable(offset, pageSize);
        Driver query = new Driver();
        query.setServiceCodes(serviceCode);
        query.setLon(lon);
        query.setLat(lat);
        query.setStatus(DriverStatus.OnLine.getValue());
        /*if (ServiceCode.BC.getCode().equals(serviceCode)) {
            query.setOpenBc(true);
        }
        if (ServiceCode.KC.getCode().equals(serviceCode)) {
            query.setOpenKc(true);
        }*/

        List<Driver> drivers = driverService.searchByDistance("", query, 100000, pageable);

        response = ResponseResult.success(response, drivers);

        return response;
    }

    /**
     * 获取司机信息
     *
     * @param parms
     * @return phoneNo司机phoneNo
     */
    @ApiVersion(value = {1})
    public ResponseObject getDriverInfo(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getDriverInfo");
        //参数验证
        if (!checkRequireParms(parms, "phoneNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        Driver query = new Driver();
        query.setPhoneNo(phoneNo);
        query.setEnabled(true);

        Driver driver = driverService.selectOne("", query);
        //司机不存在
        if (driver == null) {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        } else {
            response = ResponseResult.success(response, driver);
        }

        return response;
    }

    /**
     * 获取司机最新状态信息
     *
     * @param parms phoneNo司机phoneNo
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getHomeDriverInfo(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getHomeDriverInfo");
        //参数验证
        if (!checkRequireParms(parms, "phoneNo")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String phoneNo = ConvertUtil.parseString(parms.get("phoneNo"));
        if (StringUtils.isBlank(phoneNo)) {
            return ResponseResult.exception(response, ErrorCode.PHONE_EMPTY);
        }
        Driver query = new Driver();
        query.setPhoneNo(phoneNo);
        query.setEnabled(true);

        Driver driver = driverService.selectOne("", query);
        //司机不存在
        if (driver == null) {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
            return response;
        }
        //计算今日在线时长
        long durnation = 0;
        if (driver.getStatus() == UserStatus.OffLine.getValue()) {
            durnation = driver.getDuration();
        } else {
            //判断上一次登录时间是否在今日
            Boolean isTodayeLogin = false;
            if (driver.getLoginTime() != null && driver.getLoginTime() > 0) {
                String time = DateUtil.longToStr(driver.getLoginTime() * 1000, "yyyy-MM-dd");
                String nowtime = DateUtil.longToStr(new Date().getTime(), "yyyy-MM-dd");
                if (time.equals(nowtime)) {
                    isTodayeLogin = true;
                }
            }
            if (isTodayeLogin) {
                durnation = (SystemUtil.getAllSeconds() - driver.getLoginTime()) + driver.getDuration();
            } else {
                String begindate = DateUtil.DatetoString(new Date(), "yyyy-MM-dd 00:00:00");
                long begin = DateUtil.StringtoDate(begindate, "yyyy-MM-dd HH:mm:ss").getTime() / 1000;
                durnation = SystemUtil.getAllSeconds() - begin;
            }
        }

        int status1 = TripStatus.Complete.getValue();
        ServiceTrip cjtquery = new ServiceTrip();
        cjtquery.setUserType(PlatformUserType.DRIVER_USER.getValue());
        cjtquery.setDriverOpenId(driver.getOpenId());
        cjtquery.setStatus(status1);

        String beginDate = DateUtil.DatetoString(new Date(), "yyyy-MM-dd");
        Long start = DateUtil.StringtoDate(beginDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss").getTime() / 1000;
        Long end = DateUtil.StringtoDate(beginDate + " 24:00:00", "yyyy-MM-dd HH:mm:ss").getTime() / 1000;
        cjtquery.setStartCompleteTime(start);
        cjtquery.setEndCompleteTime(end);
        //long count = serviceTripService.selectCount("", cjtquery);

        cjtquery.setUserType(PlatformUserType.CLIENT_USER.getValue());
        List<ServiceTrip> result1 = serviceTripService.selectList("", cjtquery);
        int count = 0;
        Map<String, Object> result = new HashedMap();
        if (result1 != null && result1.size() > 0) {
            count = result1.size();
            Double income = 0.0;
            for (ServiceTrip serviceTrip : result1) {
                income = income + serviceTrip.getPayFee();
            }
            //result.put("orderNum", result1.size());
            result.put("income", income);
        } else {
            //result.put("orderNum", 0);
            result.put("income", 0.00);
        }
        result.put("orderNum", count);
        result.put("status", driver.getStatus());
        result.put("score", driver.getScore());
        result.put("durnation", durnation);
        result.put("serviceCodes", driver.getServiceCodes());

        response = ResponseResult.success(response, result);
        return response;
    }

    /**
     * 获取司机信息
     *
     * @param parms dCommonId 司机固定id
     * @return
     */
    @ApiVersion(value = {1})
    public ResponseObject getDriverInfoByCommonId(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getDriverInfoByCommonId");
        //参数验证
        if (!checkRequireParms(parms, "dCommonId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }

        String dCommonId_str = ConvertUtil.parseString(parms.get("dCommonId"));
        if (StringUtils.isBlank(dCommonId_str)) {
            return ResponseResult.exception(response, ErrorCode.DCOMMONID_EMPTY);
        }
        long dCommonId = ConvertUtil.parseLong(dCommonId_str);
        Driver query = new Driver();
        //query.setdCommonId(dCommonId);
        query.setEnabled(true);

        Driver driver = driverService.selectOne("", query);
        //司机不存在
        if (driver == null) {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        } else {
            response = ResponseResult.success(response, driver);
        }

        return response;
    }

    /**
     * 司机开启接单行程
     *
     * @param parms openId            司机openId
     *              serviceCode服务业务代码
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject openRecieveTrip(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "openRecieveTrip");
        //参数检验
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        if (StringUtils.isBlank(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
        }
        //只有包车和快车具备这个开关
        if (ServiceCode.ZC.getCode().equals(serviceCode)
                && ServiceCode.KC.getCode().equals(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_ERROR);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }


        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            /*if (ServiceCode.ZC.getCode().equals(serviceCode)) {
                entity.setOpenBc(true);
            } else if (ServiceCode.KC.getCode().equals(serviceCode)) {
                entity.setOpenKc(true);
            }*/
            entity.setLoginTime(SystemUtil.getAllSeconds());
            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //重新获取司机返回
            Driver result = driverService.getDriverByOpenId("", openId);
            response = ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        return response;
    }

    /**
     * 司机关闭接单行程
     *
     * @param parms openId            司机openId
     *              serviceCode服务业务代码
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject closeRecieveTrip(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "closeRecieveTrip");
        //参数检验
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        String serviceCode = ConvertUtil.parseString(parms.get("serviceCode"));
        if (StringUtils.isBlank(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_EMPTY);
        }
        //只有包车和快车具备这个开关
        if (ServiceCode.ZC.getCode().equals(serviceCode)
                && ServiceCode.KC.getCode().equals(serviceCode)) {
            return ResponseResult.exception(response, ErrorCode.SERVICE_CODE_ERROR);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        Boolean success = false;
        try {
            Driver entity = new Driver();
            entity.setDriverId(driver.getDriverId());
            entity.setStatus(UserStatus.OnLine.getValue());
            /*if (ServiceCode.ZC.getCode().equals(serviceCode)) {
                entity.setOpenBc(false);
            } else if (ServiceCode.KC.getCode().equals(serviceCode)) {
                entity.setOpenKc(false);
            }*/
            int row = driverService.updateByKey("", entity);
            success = row > 0;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            //重新获取司机返回
            Driver result = driverService.getDriverByOpenId("", openId);
            response = ResponseResult.success(response, result);
        } else {
            response = ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        return response;
    }

    /**
     * 获取司机收入
     *
     * @param parms{phoneNo} openId         司机openId
     * @return
     */
    @ApiVersion(value = {1})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject getIncome(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getIncome");
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = String.valueOf(parms.get("openId"));
        if (StringUtils.isEmpty(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("balance", driver.getBalance());
        result.put("cash", driver.getCash());
        result.put("income", driver.getIncome());

        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 获取收入明细记录
     *
     * @param parms{phoneNo} openId         司机openId
     *                       pageIndex      分页索引
     *                       pageSize       分页每页显示条数
     * @return
     */
    @ApiVersion(value = {1, 2, 3})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject getIncomeList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getIncomeList");
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = String.valueOf(parms.get("openId"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;

        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        RechargeRecord query = new RechargeRecord();
        query.setUserType(PlatformUserType.DRIVER_USER.getValue());
        query.setRechargeType(RechargeType.CompleteTrip.getValue());
        query.setPhoneNo(openId);

        Sort sort = new Sort(Direction.DESC, "recharge_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
        List<RechargeRecord> list = rechargeRecordService.selectList("", query, pageable);
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        if (list != null && !list.isEmpty()) {
            for (RechargeRecord record : list) {
                Map<String, Object> item = new HashMap<String, Object>();
                String prefix = StringUtils.isBlank(record.getLinkTaskNo()) ? "" : record.getLinkTaskNo().substring(0, 2);
                String serviceCodeName = "";
                if (ServiceCode.BC.getPrefix().equals(prefix)) {
                    serviceCodeName = ServiceCode.BC.getName();
                } else if (ServiceCode.KC.getPrefix().equals(prefix)) {
                    serviceCodeName = ServiceCode.KC.getName();
                } else if (ServiceCode.KD.getPrefix().equals(prefix)) {
                    serviceCodeName = ServiceCode.KD.getName();
                } else if (ServiceCode.SFC.getPrefix().equals(prefix)) {
                    serviceCodeName = ServiceCode.SFC.getName();
                } else if (ServiceCode.SWZL.getPrefix().equals(prefix)) {
                    serviceCodeName = ServiceCode.SWZL.getName();
                } else if (ServiceCode.ZXPC.getPrefix().equals(prefix)) {
                    serviceCodeName = ServiceCode.ZXPC.getName();
                }
                item.put("name", serviceCodeName);
                item.put("time", SystemUtil.secondsToDate(record.getRechargeTime(), "yyyy-MM-dd HH:mm:ss"));
                item.put("fee", record.getRechargeMoney());
                item.put("remark", record.getRemark());

                result.add(item);
            }
        }

        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 获取司机车辆图片
     *
     * @param parms
     * @return
     */
    @ApiVersion(value = {1, 2, 3})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject getCarImages(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getCarImages");
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = String.valueOf(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        DriverCarImgs query = new DriverCarImgs();
        query.setOpenId(openId);
        query.setEnabled(true);

        List<DriverCarImgs> result = driverCarImgsService.selectList("", query);

        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 获取司机评价列表
     *
     * @param parms openId    司机openId
     *              pageIndex 分页索引
     *              pageSize  分页每页现实条数
     * @return
     */
    @ApiVersion(value = {1, 2, 3})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject getCommentList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getCommentList");
        if (!checkRequireParms(parms, "openId", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = String.valueOf(parms.get("openId"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;

        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        if (!driverService.existByOpenId("", openId)) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }
        Sort sort = new Sort(Direction.DESC, "time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);

        Comment query = new Comment();
        query.setToOpenId(openId);
        query.setEnabled(true);

        List<Comment> result = commentService.selectList("", query, pageable);

        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 申请提现
     *
     * @param parms openId 司机openId
     *              cash   申请提现金额
     * @return
     */
    @ApiVersion(value = {1, 2, 3})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject applyCash(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "applyCash");
        if (!checkRequireParms(parms, "openId", "cash")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        double applyCash = ConvertUtil.parseDouble(parms.get("cash"));
        int cashType = ConvertUtil.parseInt(parms.get("cashType"), 1);
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        //申请金额必须大于0
        if (applyCash <= 0) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_APPLY_CASH_LESS_ZERO);
        }

        if (cashType == 1) {
            Driver driver = driverService.getDriverByOpenId("", openId);
            //司机不存在
            if (driver == null) {
                return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
            }
            //余额不足
            if (driver.getBalance() == null || driver.getBalance() < applyCash) {
                return ResponseResult.exception(response, ErrorCode.DRIVER_BALANCE_NOT_ENOUGH);
            }
            //判断是否已经有申请记录
            CashApply query = new CashApply();
            query.setApplyUser(openId);
            query.setApplyUserType(PlatformUserType.DRIVER_USER.getValue());
            query.setStatus(CashApplyStatus.Apply.getValue());

            long count = cashApplyService.selectCount("", query);
            if (count > 0) {
                return ResponseResult.exception(response, ErrorCode.DRIVER_EXIST_CASH_APPLY);
            }
        } else if (cashType == 2) {
            TicketUser ticketUser = ticketUserService.getTicketInfoByPhoneNo("", openId);
            //司机不存在
            if (ticketUser == null) {
                return ResponseResult.exception(response, ErrorCode.TICKET_USER_NULL);
            }
            //余额不足
            if (ticketUser.getBalance() == null || ticketUser.getBalance() < applyCash) {
                return ResponseResult.exception(response, ErrorCode.DRIVER_BALANCE_NOT_ENOUGH);
            }
            //判断是否已经有申请记录
            CashApply query = new CashApply();
            query.setApplyUser(openId);
            query.setApplyUserType(PlatformUserType.TICKET_USER.getValue());
            query.setStatus(CashApplyStatus.Apply.getValue());

            long count = cashApplyService.selectCount("", query);
            if (count > 0) {
                return ResponseResult.exception(response, ErrorCode.DRIVER_EXIST_CASH_APPLY);
            }
        }

        Boolean success = false;
        try {
            CashApply entity = new CashApply();
            entity.setApplyUser(openId);
            entity.setApplyCash(applyCash);
            entity.setApplyFrom(2);//申请来源 1后台 2APP
            if (cashType == 1) {
                entity.setApplyUserType(PlatformUserType.DRIVER_USER.getValue());
            } else if (cashType == 2) {
                entity.setApplyUserType(PlatformUserType.TICKET_USER.getValue());
            }
            entity.setApplyTime(SystemUtil.getAllSeconds());
            entity.setStatus(CashApplyStatus.Apply.getValue());
            entity.setCashType(cashType);

            int row = cashApplyService.insert("", entity);
            success = row > 0;

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            ResponseResult.success(response, "申请成功，请等待审核");
        } else {
            ResponseResult.exception(response, ErrorCode.DRIVER_CASH_APPLY_FAILED);
        }

        return response;
    }

    /**
     * 提现记录
     *
     * @param parms openId    司机openId
     *              pageIndex 分页索引
     *              pageSize  每页条数
     * @return
     */
    @ApiVersion(value = {1, 2, 3})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject getCashRecordList(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getCashRecordList");
        if (!checkRequireParms(parms, "openId", "pageIndex", "pageSize")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        int pageIndex = ConvertUtil.parseInt(parms.get("pageIndex"), 1);
        int pageSize = ConvertUtil.parseInt(parms.get("pageSize"), 10);
        int cashType = ConvertUtil.parseInt(parms.get("cashType"), 1);
        pageIndex = Math.max(pageIndex, 1);
        pageSize = Math.max(pageSize, 1);
        int offset = (pageIndex - 1) * pageSize;

        Sort sort = new Sort(Direction.DESC, "cash_time");
        CustomPageable pageable = new CustomPageable(offset, pageSize, sort);
        CashApply query = new CashApply();
        query.setApplyUser(openId);
        query.setCashType(cashType);
        if (cashType == 1) {
            query.setApplyUserType(PlatformUserType.DRIVER_USER.getValue());
        } else if (cashType == 2) {

        }
        List<CashApply> result = cashApplyService.selectList("", query, pageable);

        ResponseResult.success(response, result);

        return response;
    }

    /**
     * 获取绑定银行卡
     *
     * @param parms openId 司机openId
     * @return
     */
    @ApiVersion(value = {1, 2, 3})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject getBindBankCard(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "getBindBankCard");
        if (!checkRequireParms(parms, "openId")) {
            return ResponseResult.exception(response, ErrorCode.REQUEST_PARMS_ERROR);
        }
        String openId = ConvertUtil.parseString(parms.get("openId"));
        if (StringUtils.isBlank(openId)) {
            return ResponseResult.exception(response, ErrorCode.OPENID_EMPTY);
        }
        Driver driver = driverService.getDriverByOpenId("", openId);
        if (driver == null) {
            return ResponseResult.exception(response, ErrorCode.DRIVER_NOT_EXIST);
        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("userName", StringUtils.isBlank(driver.getTrueName()) ? "" : driver.getTrueName());
        result.put("cardNo", StringUtils.isBlank(driver.getBankCard()) ? "" : driver.getBankCard());
        result.put("bankName", StringUtils.isBlank(driver.getBankName()) ? "" : driver.getBankName());

        ResponseResult.success(response, result);

        return response;
    }


    /**
     * 微信司机导入系统中
     *
     * @param parms openId 司机openId
     * @return
     */
    @ApiVersion(value = {1, 2, 3})
    @CheckToken(check = true, tokenKey = "openId", platform = RequestPlatform.driver)
    public ResponseObject importDriver(Map<String, Object> parms) {
        ResponseObject response = ResponseResult.create("driver", "importDriver");

        //查询司机列表
        List<PlatformDriver> listdriver = platformDriverService.selectAll("");
        for (PlatformDriver driver : listdriver) {
            String phoneNo = driver.getDriverPhone();

            Driver query1 = new Driver();
            query1.setPhoneNo(phoneNo);
            Driver driver1 = driverService.selectOne("", query1);
            if (driver1 != null) {
                continue;
            }

            Driver entity = new Driver();
            String slat = SystemUtil.generateSalt(6);
            //生成openId
            String openId = OpenIdUtil.encrypt(entity.getPhoneNo() + entity.getIdCard(), SystemUtil.getAllSeconds(), slat);
            entity.setOpenId(openId);
            String token = TokenUtil.encrypt(phoneNo, openId);
            entity.setToken(token);
            entity.setPhoneNo(phoneNo);
            entity.setIdCard(driver.getLicenseId());
            entity.setTrueName(driver.getDriverName());
            //entity.setPwd();
            entity.setSlat(slat);
            entity.setSex(driver.getDriverGender());
            //entity.setBankCard(bankCard);
            //entity.setBankName(bankName);
            //计算驾龄
            String driveAgeStr = driver.getGetDriverLicenseDate();
            if (!TextUtils.isEmpty(driveAgeStr)) {
                try {
                    Date date = DateUtil.StringtoDate(driveAgeStr, "yyyyMMdd");
                    int driveAge = new Date().getYear() - date.getYear();
                    if (driveAge > 0) {
                        entity.setDriveAge(driveAge + 1);
                    } else {
                        entity.setDriveAge(1);
                    }
                } catch (Exception e) {

                }
            }
            entity.setDriveCret(driver.getLicenseId());
            //entity.setNetCert(netCert);
            //entity.setRunCert(runCert);

            //entity.setLon(lon);
            //entity.setLat(lat);
            //entity.setHeadImg(headImg);
            //entity.setIdCardFrontImg(idCardFrontImg);
            //entity.setIdCardBackImg(idCardBackImg);
            //entity.setDriveCretImg(driveCretImg);

            //默认值
            entity.setStar(3.0);
            entity.setBalance(0.0);
            entity.setIncome(0.0);
            entity.setCash(0.0);
            entity.setStatus(DriverStatus.OffLine.getValue());
            entity.setOrderCount(0);
            entity.setCancelTripTimes(0);
            entity.setDisableDays(0);
            entity.setDisableDate(0L);
            entity.setOperator("城际通系统导入");
            entity.setOperateTime(SystemUtil.getAllSeconds());
            entity.setEnabled(true);
            entity.setSourceType(1);
            entity.setScore(100.0);

            //查询车辆信息
            Vehicle query = new Vehicle();
            query.setDriverPhone(driver.getDriverPhone());
            Vehicle vehicle = vehicleService.selectOne("", query);
            if (vehicle != null) {
                entity.setBindCar(true);
                entity.setCheckState(DriverCheckStatus.CheckSusses.getValue());
                entity.setCarNo(vehicle.getVehicleNo());
                entity.setCarRank(vehicle.getModel());
                entity.setCarType(vehicle.getVehicleType());
                entity.setCarColor(vehicle.getPlateColor());
                entity.setCarBrand(vehicle.getBrand());
                entity.setCarSeats(Integer.parseInt(vehicle.getSeats() + ""));
            } else {
                entity.setBindCar(false);
                entity.setCheckState(DriverCheckStatus.WaitCheck.getValue());
            }
            //手机注册，默认为城际通
            entity.setServiceCodes(ServiceCode.CJT.getCode());
            entity.setServiceNames(ServiceCode.CJT.getName());
            driverService.insert("", entity);

            //更新密码
            //update ldk_driver d set pwd=(select passWord from hdcx_driver_user u where d.phone_no=u.DriverPhone) where source_type=1
            //是否启用司机账号
            //update ldk_driver d set enabled=0 where source_type=1 and phone_no in (select DriverPhone from hdcx_driver_user u where d.phone_no=u.DriverPhone and status=0)
        }


        ResponseResult.success(response, "");

        return response;
    }
}
